<script setup lang="ts">
import { MdPreview, MdCatalog } from 'md-editor-v3';
import MdEditor from "~/components/MdEditor.vue";
// import { isClient } from '@vueuse/shared'
// import picker compopnent
import EmojiPicker from 'vue3-emoji-picker'
// import {UseDraggable as Draggable} from "~/components/draggable";
// import css
import 'vue3-emoji-picker/css'
// preview.css相比style.css少了编辑器那部分样式
// import 'md-editor-v3/lib/preview.css';
import 'md-editor-v3/lib/style.css';
import {VsLoadingFn} from "vuesax-alpha";
import type {BlogItem, DiscussItem, PageData, ResponseData} from "~/types";
import Inputer from "~/components/Inputer.vue";
// import {Motion} from 'motion-v'
type getElFunc = ()=>HTMLElement
const id = 'preview-only';
const text = ref('');
const router = useRouter()
const detailContainer = useTemplateRef('detailContainer')
const discussVal = ref('')
const nickName = ref('')
const total = ref(0)
const size =  ref(20)
const currentPage = ref(1)
const commentContent = useTemplateRef('commentContent')
const discussList = ref<DiscussItem[]>([])
const getViewportEl: undefined|getElFunc = inject('getViewportEl')
const categoryContainer = useTemplateRef<HTMLElement>('categoryContainer')
const blogDetail = ref<BlogItem>({
  blogDesc: '',
  blogTitle: '',
  coverUrl: '',
  createDate: '',
  discussCount: 0,
  editorType: 0,
  enable: false,
  id: '',
  tagsList: [],
  updateDate: '',
})
const getNowTheme = inject('getNowTheme') as ()=> 'dark'|'light'
const query = useRoute().query as {id:string,discuss: '0'|'1'}
const handle = useTemplateRef<HTMLElement>('handle')
const dragController = useTemplateRef<HTMLElement>('dragController')
const clientWidth = useWindowSize().width
const viewPortEl = ref<HTMLElement>()

function goHome() {
  router.back()
}
const nowTheme = computed(()=> getNowTheme())
function getArticleContent(){
  //   获取文章内容
  const loadingFn = VsLoadingFn({
    target: '#detailContainer',
    type: 'circles',
    // text: '玩命加载中',
    scale: '1.2',
  })
  const loadingBar = useLoadingBar();
  loadingBar.start()
  // const params = new URLSearchParams({id: query.id})
  $fetch('/api/blogs/getBlogContent',{
    method:'get',
    query: {id: query.id}
  }).then(res => {
    const resData = res as unknown as ResponseData<BlogItem>;
    blogDetail.value = resData.data;
    text.value = blogDetail.value?.blogContent || ''
    loadingBar.finish()
    getNowBlogDiscuss()
  }).catch(()=> {
    loadingBar.error()
  }).finally(()=> {
    loadingFn.close()
  })
}
function handleUpdateShow(){

}
function onSelectEmoji(emoji:any){
  // console.log(emoji)
  discussVal.value+=emoji.i;
}
function handlePageChange(val:number){
  currentPage.value = val;
  getNowBlogDiscuss()
}
function handleSizeChange(val:number){
  size.value = val;
  currentPage.value = 1
  getNowBlogDiscuss()
}
function getNowBlogDiscuss(){
  const loadingFn = VsLoadingFn({
    target: commentContent.value,
    type: 'circles',
    // text: '玩命加载中',
    scale: '1.2',
  })
  // const params = new URLSearchParams({id: query.id})
  $fetch('/api/discuss/getBlogDiscuss',{
    method:'get',
    query: {
      blogId: blogDetail.value?.id,
      page: currentPage.value,
      size: size.value
    }
  }).then(res => {
    const resData = res as unknown as ResponseData<PageData<DiscussItem[]>>;
    discussList.value = resData.data.list || []
    total.value = resData.data.total || 0
    loadingFn.close()
  }).finally(()=> {
    loadingFn.close()
  })
}
function handleAddComment() {
  const val = unref(discussVal);
  const commenter = unref(nickName);
  // console.log(val,commenter)
  if(!val || !commenter) {
    VsNotification({
      progressAuto: true,
      color: 'danger',
      position: 'top-center',
      title: '校验错误',
      content:
          '【昵称】和【内容】必须填写！',
    })
    return
  }
  $fetch('/api/discuss/addDiscuss',{
    method:'post',
    body: {
      blogId: Number(blogDetail.value?.id),
      content: val,
      commenter: commenter
    }
  }).then(res => {
    VsNotification({
      progressAuto: true,
      color: 'success',
      position: 'top-center',
      title: '发布评论',
      content:
          '发布成功！',
    })
    discussVal.value = '';
    nickName.value = '';
    getNowBlogDiscuss()
  })
}
function getViewport() {
  if(getViewportEl){
    return getViewportEl()
  }
  return '#viewport'
}

onMounted(()=> {
  if(query.discuss == '1'){
    //   滚动到评论位置
    commentContent.value?.scrollIntoView({
      behavior: 'smooth'
    })
  }else{
    getViewportEl?.()?.scrollTo({
      top: 0,
      left: 0,
      behavior: 'smooth'
    })
  }
  getArticleContent()
  viewPortEl.value = document.getElementById('detailContainer')!

  // console.log('category',categoryEl.value,categoryEl.value?.$el)
  // if(categoryEl.value?.$el){
  //   const el:HTMLElement = categoryEl.value.$el
  //   // 目录可拖拽
  //   useDraggable(el, {
  //     initialValue: {
  //       x: 0,
  //       y: 0
  //     },
  //     onMove: ({ x, y }) => {
  //       el.style.setProperty('transform', `translate(${x}px, ${y}px)`)
  //     },
  //   })
  // }

})

// 目录也相关逻辑
const showCatalog = ref(true)
function toggleCatelog() {
  showCatalog.value = !showCatalog.value
}

const onUploadImg = async (files:File[], callback:(res:any[])=>any) => {
  const res = await Promise.all(
      files.map((file):Promise<any> => {
        console.log(file)
        const form = new FormData();
        form.append('file',file)
        return new Promise((rev, rej) => {
              $fetch('/api/oss/upload', {
                body: form,
                method: 'POST',
                headers: {
                  'Content-Type': 'multipart/form-data',
                },
              })
              .then((res) => rev(res))
              .catch((error) => rej(error));
        });
      })
  );

  callback(res.map((item:any) => item.data?.list[0]?.url));
};
</script>
<template>
  <div class="w-full">
<!--    <ClientOnly>-->
      <div class="detail-container pr-6 pl-6 lg:pr-10 lg:pl-10" ref="detailContainer" id="detailContainer">
        <div class="guide-header">
          <vs-button color="whatsapp" size="large" type="floating" @click="goHome">
            <i class="bx bx-left-arrow-alt" />
            <template #animate>
              首页
            </template>
          </vs-button>

          <span class="detail-title" style="margin-left: 8px">
        {{blogDetail.blogTitle}}
      </span>
          <n-space class="detail-desc m-4">
            <n-tag> 创建日期：{{blogDetail.createDate}} </n-tag>
            <n-tag> 最后更新：{{blogDetail.updateDate}}  </n-tag>
          </n-space>
        </div>
        <span class="text-gray-500"> 说明：{{blogDetail.blogDesc}} </span>
        <MdPreview :theme="nowTheme" :previewTheme="nowTheme==='dark'?'dark':'cyanosis'"
                   showCodeRowNumber
                   readOnly
                   :codeFoldable="false"
                   :id="id" :modelValue="text" />
        <n-divider title-placement="left" class="text-gray-600 mt-6 dark:text-white">
          END
        </n-divider>
        <n-divider title-placement="left" class="text-gray-600 mt-6 dark:text-white">
          吐个槽吧
        </n-divider>
        <div class="comment-container">
          <div class="flex justify-start align-middle items-center mb-3">
        <span class="mb-0 whitespace-nowrap">
          昵称：
        </span>
            <Inputer
                v-model="nickName"
                type="textarea"
                placeholder="吐个槽吧"
                show-count
                :maxlength="20"
                class="mb-0"
                style="max-width: 600px"
                :autosize="{
        minRows: 3,
      }"
            />
          </div>
          <div class="flex justify-start align-middle items-start mb-3">
          <span class="mb-0 whitespace-nowrap">
            内容：
          </span>
            <MdEditor
                v-model:model-value="discussVal"
                height="30vh"
                style="width: 100%;max-width:600px"
                :options="{
                  height: '100%',
                  theme: nowTheme === 'dark' ? 'dark' : 'classic',
                }"
            ></MdEditor>
          </div>
          <div class="flex ml-8">
            <n-popover
                placement="bottom"
                trigger="click"
            >
              <template #trigger>
                <vs-button icon color="success" type="floating" shape="circle">
                  <i class="bx bxs-smile" />
                </vs-button>
              </template>
              <EmojiPicker :native="true" @select="onSelectEmoji" />
            </n-popover>
            <n-tooltip
                placement="bottom"
                trigger="hover"
            >
              <template #trigger>
                <vs-button shape="circle" icon type="floating" @click="handleAddComment">
                  <i class="bx bxs-send" />
                </vs-button>
              </template>
              <span> 戳我发送</span>
            </n-tooltip>
          </div>
          <div class="comment-content mt-5" ref="commentContent">
            <n-list bordered>
              <n-list-item v-for="item in discussList" :key="item.id" class="!items-start">
                <template #prefix>
                  <n-avatar
                      size="large"
                      round
                      color="#195bff"
                      :src="item.commenterAvatar"
                  >{{(item.commenter || '').slice(0,1)}}</n-avatar>
                </template>
                <!--            <template #suffix>-->

                <!--            </template>-->
                <n-thing :title="item.content" :title-extra="item.commenter" :description="item.createDate" description-class="text-gray-500">
                  <template #header-extra>
                    <span class="whitespace-nowrap">{{item.commenter}}</span>
                  </template>
                  <template #header>
                    <MdPreview :theme="nowTheme" :previewTheme="nowTheme==='dark'?'dark':'cyanosis'"
                               showCodeRowNumber
                               readOnly
                               :codeFoldable="false"
                               :modelValue="item.content" />
                  </template>
                </n-thing>
              </n-list-item>
            </n-list>
          </div>
          <!--        分页器-->
          <vs-pagination
              class="w-11/12 m-auto text-center mb-8 mt-8 fe-pagination"
              v-model:current-page="currentPage"
              :layout="['total', 'prev', 'pager', 'next', 'jumper', 'sizes']"
              :total="total"
              :page-size="size"
              @page-change="handlePageChange"
              @size-change="handleSizeChange"
          />
        </div>
        <ClientOnly>
          <!--        目录-->
            <n-el class="category" ref="category" :class="{
            hide: !showCatalog
          }">
              <div class="category-main">
                目录
                <MdCatalog :editorId="id" :scrollElement="getViewport()" />
              </div>
              <div class="category-right flex justify-center mt-4">
                <vs-button size="mini" type="floating" color="whatsapp" icon shape="circle" @click="toggleCatelog">
                  <i class="bx" :class="{
                    'bxs-chevrons-right': showCatalog,
                    'bxs-chevrons-left': !showCatalog
                  }" />
                </vs-button>
              </div>
            </n-el>
        </ClientOnly>

<!--        </n-el>-->
<!--        <Draggable-->
<!--            class="category opacity-0 sm:w-48 md:w-64 sm:opacity-100"-->
<!--            :initial-value="{ x: clientWidth*0.8, y: 120 }"-->
<!--            :prevent-default="true"-->
<!--            :handle="handle"-->
<!--            stopPropagation-->
<!--        >-->
<!--          -->
<!--        </Draggable>-->
      </div>
<!--    </ClientOnly>-->
  </div>


</template>
<style lang="scss">
.detail-container{
  width: 100%;
  margin: 16px auto;
  //box-shadow: 0px 0px 7px 0px rgba(0, 0, 0, 0.1);
  // border: 1px solid #e2e2e2;
  //padding: 16px;
  border-radius: var(--vs-radius);
  min-height: 30vh;
}
.detail-title{
  font-size: var(--vs-font-size-extra-large);
}
.guide-header{
  //margin-top: 12px;
  display: flex;
  justify-content: flex-start;
  align-content: center;
  align-items: center;
  flex-wrap: wrap;
  .detail-title{
    flex: 1 1 auto;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    flex-wrap: wrap;
  }
}
.category{
  position: fixed;
  right: 1vw;
  top: 16vh;
  backdrop-filter: blur(4px);
  border-radius: 10px;
  background-color: rgba(175, 197, 255, 0.4);
  padding: 16px;
  transition: all .6s;
  z-index: 1999;
  max-width: 20em;
  .category-right{
    transition: all .6s;
  }
  &.hide{
    transform: translateX(calc(100% + 1vw));
    .category-right{
      transform: translateX(calc(-100% - 1vw));
    }
  }
  box-shadow: var(--vs-shadow);
}
.draggable{
  position: relative;
  cursor: move;
  transition: transform 0.2s ease-in-out;
}
</style>